let workTime = 1000 * 60 * 60

const setCycle = (time) =>
	setInterval(() => {
		const opt = {
			type: 'basic',
			title: 'Is Time To Relax！',
			message: '这是猫猫的提醒！离开屏幕休息会儿吧！',
			iconUrl: 'police.png',
		}
		chrome.notifications.create(opt, () => {
			chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
				// 向该tab发送消息
				chrome.tabs.sendMessage(tabs[0].id, { relax: true }, function () {
					// return true
				})
			})
		})
	}, time)

let id

chrome.storage.sync.get(['workTime'], (res) => {
	if (res.workTime) {
		workTime = res.workTime
		id = setCycle(workTime)
		return
	}
	chrome.storage.sync.set({ workTime: workTime }, () => {
		id = setCycle(workTime)
	})
})

function setWorkTime(newTime) {
	clearInterval(id)
	id = setCycle(newTime)
	chrome.storage.sync.set({ workTime: newTime })
}
let clockId
const clock = () => {
	const opt = {
		type: 'basic',
		title: '吃饭时间到！',
		message: '吃饭时间！快去吃饭吧！',
		iconUrl: 'police.png',
	}
	chrome.notifications.create(opt, () => {
		chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
			// 向该tab发送消息
			chrome.tabs.sendMessage(tabs[0].id, { relax: true }, function () {
				// return true
			})
		})
	})
	clearTimeout(clockId)
	clockId = setTimeout(() => {
		clock()
	}, 1000 * 60 * 60 * 24)
}
const todayStart = () => {
	const y = new Date().getFullYear()
	const m = new Date().getMonth()
	const d = new Date().getDate()

	return new Date(y, m, d).getTime()
}
let dinnerId
function setDinnerTime(time) {
	if (!time) {
		return
	}
	clearTimeout(dinnerId)
	clearTimeout(clockId)
	chrome.storage.sync.set({ dinnerTime: time })
	time = time * 1000 * 60 * 60
	if (todayStart() + time > Date.now()) {
		dinnerId = setTimeout(() => {
			clock()
		}, todayStart() + time - Date.now())
	} else {
		dinnerId = setTimeout(() => {
			clock()
		}, todayStart() + time + 1000 * 60 * 60 * 24 - Date.now())
	}
}
chrome.storage.sync.get(['dinnerTime'], (res) => {
	res.dinnerTime && setDinnerTime(res.dinnerTime)
})
